import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	TreeSelect,
	message,
	Radio,
	RadioChangeEvent,
} from 'antd'
import React, {memo, useEffect, useState} from 'react'
import {history} from 'umi'
import styles from '@/assets/common/css/page.less'
import {translateDataToTree} from '@/utils/common/index'
import {getMenuList, addMenu, editMenu, viewMenu} from '@/service/system/menu'
import IconSelect from './icon'

const {Panel} = Collapse
const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

export default memo((props: any) => {
	const [treeData, setTreeData] = useState()
	const [form] = Form.useForm()
	const [menuType, setMenuType] = useState<number>()
	const [idData, setIdData] = useState('')
	const [type, setType] = useState<string>()
	const [icon, setIcon] = useState<string>()

	// 获取上级菜单
	const onMenuListFun = () => {
		getMenuList().then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setTreeData([
					{name: '根节点', id: 0, pid: -1, children: [...list]},
				] as any)
			}
		})
	}
	const onViewFun = (merchantId: string) => {
		viewMenu(merchantId).then((res: any) => {
			if (res?.success) {
				setMenuType(res?.data?.menuType)
				setIcon(res?.data?.icon)
				form.setFieldsValue({...res.data})
			}
		})
	}
	//
	const onMenuTypeChange = ({target: {value}}: RadioChangeEvent) => {
		setMenuType(value)
		form.setFieldsValue({
			...form,
			menuType: value,
		})
	}

	useEffect(() => {
		const {id} = props.location.query
		onMenuListFun()
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
			setMenuType(0)
			form.setFieldsValue({...form, menuType: 0})
		} else {
			setType('edit')
		}
		if (id) {
			setIdData(id)
			onViewFun(id)
		}
	}, [])
	// 表单提交
	const submit = async () => {
		const formData = await form.validateFields()
		let pramas
		if (menuType === 0) {
			pramas = Object.assign(formData, {
				componentPath: '',
				path: '',
			})
		} else if (menuType === 1) {
			pramas = formData
		} else {
			pramas = Object.assign(formData, {
				componentPath: '',
				path: '',
				sort: '',
				icon: '',
			})
		}
		if (!idData) {
			if (!formData.parentId) {
				formData.parentId = 0
			}
			// 新增菜单
			addMenu({...pramas})
				.then((res: any) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		} else {
			// 编辑菜单
			editMenu(idData, {
				...pramas,
				parentId: formData.parentId ? formData.parentId : 0,
			})
				.then((res: any) => {
					if (res.success) {
						message.success(res?.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}
	return (
		<div className={styles.page}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '100px'}}
							labelAlign="right"
							labelWrap
							initialValues={{remember: true}}
							autoComplete="off"
							disabled={type === 'view'}>
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 24}}
									lg={{span: 24}}>
									<Form.Item
										label="类型"
										name="menuType"
										rules={[
											{
												required: true,
												message: '请选择类型',
											},
										]}>
										<Radio.Group
											name="menuType"
											onChange={onMenuTypeChange}>
											<Radio value={0}>目录</Radio>
											<Radio value={1}> 菜单</Radio>
											<Radio value={2}> 按钮</Radio>
										</Radio.Group>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="菜单名称"
										name="name"
										rules={[
											{
												required: true,
												message: '请输入菜单名称',
											},
										]}>
										<Input
											placeholder="请输入"
											maxLength={60}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="上级菜单" name="parentId">
										<TreeSelect
											showSearch
											treeNodeFilterProp="name"
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择"
											allowClear
											treeDefaultExpandAll
											fieldNames={{
												label: 'name',
												value: 'id',
											}}
											treeDataSimpleMode
											treeData={treeData}
										/>
									</Form.Item>
								</Col>
								{[0, 1].includes(menuType!) ? (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="当前路径"
											name="componentPath"
											rules={[
												{
													required: true,
													message: '请输入当前路径',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
								) : null}
								{menuType === 1 ? (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="菜单URL"
											name="path"
											rules={[
												{
													required: true,
													message: '请输入菜单URL',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
								) : null}
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="授权标识"
										name="code"
										rules={[
											{
												required: true,
												message: '请输入授权标识',
											},
										]}>
										<Input
											placeholder="请输入"
											maxLength={60}
										/>
									</Form.Item>
								</Col>
								{menuType !== 2 ? (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="排序号"
											name="sort"
											rules={[
												{
													required: true,
													message: '请输入排序号',
												},
											]}>
											<Input
												placeholder="请输入"
												maxLength={5}
											/>
										</Form.Item>
									</Col>
								) : null}
								{/* 图标暂时没啥用，先注释 */}
								{/* {menuType !== 2 ? (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="图标"
											name="icon"
											rules={[
												{
													required: true,
													message: '请输入图标',
												},
											]}>
											<IconSelect
												defValue={icon}
												callBack={(res: any) => {
													form.setFieldsValue({
														icon: res,
													})
													setIcon(res)
												}}
											/>
										</Form.Item>
									</Col>
								) : null} */}
							</Row>
						</Form>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					<Button type="primary" htmlType="submit" onClick={submit}>
						保存
					</Button>
					<Button
						onClick={(e) => {
							e.stopPropagation()
							history.goBack()
						}}>
						取消
					</Button>
				</div>
			</div>
		</div>
	)
})
